var express = require('express')
const sqlQuery = require('../../module/sqlQuery')
const cryptoMD5 = require('../../module/cryptoMD5')
var router = express.Router()

/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource')
})
router.get('/register', function (req, res, next) {
  res.render('login/register.ejs')
})
router.post('/register', async function (req, res, next) {
  const { username, password } = req.body
  const sqlStr = `select * from user where username='${username}'`
  const results = await sqlQuery(sqlStr)
  if (results.length != 0) {
    res.render('info/info.ejs', {
      title: '用户信息',
      content: '该用户已存在',
      hrefUrl: '/rl/register',
      hrefTitle: '跳往注册页',
      info:''
    })
  } else {
    const sqlStr = `insert into user (id,username,password,roleid,status) values (?,?,?,?,?)`
    const results = await sqlQuery(sqlStr, [
      new Date().getTime(),
      username,
      cryptoMD5(password),
      1,
      1,
    ])
    console.log(results)
    res.render('info/info.ejs', {
      title: '用户信息',
      content: '注册成功',
      hrefUrl: '/rl/login',
      hrefTitle: '跳往登录页',
      info:''
    })
  }
})

router.get('/login', function (req, res, next) {
  res.render('login/login.ejs')
})
router.post('/login', async function (req, res, next) {
  const { username, password } = req.body
  const sqlStr = `select * from user where username='${username}' and password='${cryptoMD5(
    password
  )}'`
  const results = await sqlQuery(sqlStr)
  if (results.length > 0) {
    req.session.username = username
    req.session.userid=results[0].id
    res.render('info/info.ejs', {
      title: '用户信息',
      content: '登录成功',
      hrefUrl: '/admin',
      hrefTitle: '跳往管理主页',
      info:''
    })
  } else {
    res.render('info/info.ejs', {
      title: '用户信息',
      content: '用户名或密码错误',
      hrefUrl: '/rl/login',
      hrefTitle: '跳往登录页',
      info:''
    })
  }
})

router.get('/logout', function (req, res, next) {
  delete req.session.username
  delete req.session.userid

  res.render('login/login.ejs')
})

module.exports = router
